import { Button, Flex, Card, Space, Avatar,Badge, Tooltip,Tag, theme,Carousel,Descriptions, Empty, Divider,Col,Row, Tour, QRCode, Input, Segmented, Statistic, Timeline } from 'antd';
import { SearchOutlined,UserOutlined,ClockCircleOutlined,CloseCircleOutlined,PlusOutlined,TwitterOutlined,AntDesignOutlined,EllipsisOutlined,LikeOutlined,ArrowDownOutlined } from '@ant-design/icons';
import { useEffect, useRef, useState } from 'react';

/**
 * 1.Avatar 头像
 * 2.Carousel 轮播图
 * 3.Descriptions 描述列表
 * 4.Tour 漫游式引导
 * 5.QRCode 二维码
 * 6.Segmented 分段控制器
 * 7.Statistic 统计数值 AND 倒计时Countdown 
 * 8.Tag 标签
 * 9.Tag 可以动态添加修改的标签
 * 10.TimeLine 时间轴
 * 11.Tooltip  文字提示
 */

/**
 * Avatar 头像
 */
const AvatarWidget =()=>{
    return(
      <Card 
      title="Avatar 头像 & 空状态"
      style={{
        width:400
      }}
      >
        <Space size={20}>
            <Avatar size={"large"} shape="square" icon={<UserOutlined />}/>
            <Avatar size={"large"} shape="circle" icon={<UserOutlined />}/>

            <Badge count={24}>
                <Avatar size={50} shape="square" icon={<UserOutlined/>}/>
            </Badge>

            <Avatar.Group>
                <Avatar src="https://api.dicebear.com/7.x/miniavs/svg?seed=1"/>
                <a href='https://www.baidu.com'>
                    <Avatar
                    style={{
                        backgroundColor:"#f56a00"
                    }}
                    >KK</Avatar>
                </a>
                <Tooltip title="Ant User" placement='top'>
                    <Avatar style={{backgroundColor:'#87d068'}} icon={<UserOutlined />}/>
                </Tooltip>
                <Avatar style={{ backgroundColor: '#1677ff' }} icon={<AntDesignOutlined />} />
            </Avatar.Group>
        </Space>

        <Divider orientation={"center"}>空状态</Divider>

        <Empty/>

        <Divider orientation={"center"}>自定义空状态</Divider>

        <Empty
        image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg"
        imageStyle={{
            height:60
        }}
        description={
            <span>
                Customize <a href="#API">Description</a>
            </span>
        }
        >
            <Button type="primary">Create Now</Button>
        </Empty>

      </Card>
    )
}

/**
 * Carousel 轮播图
 */
const CarouselWidget=()=>{
    const contentStyle={
        margin:0,
        height:"160px",
        color:"#fff",
        lineHeight:"160px",
        textAlign:"center",
        background:"#364d79"
    }
    const onChange=(currentSlide)=>{
        console.log(currentSlide)
    }
    return(
        <Card title="Carousel 跑马灯 " style={{width:400}}>
            <h3>横向</h3>
            <Carousel afterChange={onChange} dotPosition={"bottom"} autoplay arrows>
                <div>
                    <h3 style={contentStyle}>1</h3>
                </div>
                <div>
                    <h3 style={contentStyle}>2</h3>
                </div>
                <div>
                    <h3 style={contentStyle}>3</h3>
                </div>
                <div>
                    <h3 style={contentStyle}>4</h3>
                </div>
            </Carousel>

            <h3>竖向</h3>
            <Carousel 
            afterChange={onChange} 
            dotPosition={"left"} 
            autoplay 
            autoplaySpeed={1000}
            arrows 
            effect={"scrollx"}
            >
                <div>
                    <h3 style={contentStyle}>1</h3>
                </div>
                <div>
                    <h3 style={contentStyle}>2</h3>
                </div>
                <div>
                    <h3 style={contentStyle}>3</h3>
                </div>
                <div>
                    <h3 style={contentStyle}>4</h3>
                </div>
            </Carousel>
            
        </Card>
    )
}

/**
 * Descriptions 描述列表
 */
const DescriptionsWidget =()=>{
    const items = [
        {
          key: '1',
          label: 'Product',
          children: 'Cloud Database',
        },
        {
          key: '2',
          label: 'Billing Mode',
          children: 'Prepaid',
        },
        {
          key: '3',
          label: 'Automatic Renewal',
          children: 'YES',
        },
        {
          key: '4',
          label: 'Order time',
          children: '2018-04-24 18:00:00',
        },
        {
          key: '5',
          label: 'Usage Time',
          children: '2019-04-24 18:00:00',
          span: 2,
        },
        {
          key: '6',
          label: 'Status',
          children: <Badge status="processing" text="Running" />,
          span: 3,
        },
        {
          key: '7',
          label: 'Negotiated Amount',
          children: '$80.00',
        },
        {
          key: '8',
          label: 'Discount',
          children: '$20.00',
        },
        {
          key: '9',
          label: 'Official Receipts',
          children: '$60.00',
        },
        {
          key: '10',
          label: 'Config Info',
          children: (
            <>
              Data disk type: MongoDB
              <br />
              Database version: 3.4
              <br />
              Package: dds.mongo.mid
              <br />
              Storage space: 10 GB
              <br />
              Replication factor: 3
              <br />
              Region: East China 1
              <br />
            </>
          ),
        },
      ];
    return(
        <Card title="Descriptions 描述列表">
            <Descriptions title="User Info" bordered items={items}/>
        </Card>
    )
}

/**
 * Tour 漫游式引导
 */
const TourWidget =()=>{
    const ref1 = useRef(null)
    const ref2 = useRef(null)
    const ref3 = useRef(null)

    const [open,setOpen] = useState(false)

    const steps = [
        {
            title:"升级",
            description:"把你的文件放到这里",
            cover:(
                <img
                alt="tour.png"
                src="https://user-images.githubusercontent.com/5378891/197385811-55df8480-7ff4-44bd-9d43-a7dade598d70.png"
                />
            ),
            target:()=>ref1.current
        },
        {
            title: 'Save',
            description: 'Save your changes.',
            target: () => ref2.current,
        },
        {
            title: 'Other Actions',
            description: 'Click to see other actions.',
            target: () => ref3.current,
        },
    ]

    return(
        <Card title="Tour 漫游式引导">
            <Button type="primary" onClick={() => setOpen(true)}>
                开始引导
            </Button>
            <Divider />
            <Space>
                <Button ref={ref1}>上传文件</Button>
                <Button ref={ref2} type='primary'>保存文件</Button>
                <Button ref={ref3} icon={<EllipsisOutlined />}>保存文件</Button>
            </Space>
            <Tour open={open} onClose={()=>setOpen(false)} steps={steps}/>
        </Card>
    )
}

/**
 * QRCode 二维码
 */
const QRCodeWidget=()=>{
    const[text,setText]=useState("https://ant.design/")
    return(
        <Card title="QRCode 二维码">
            <Space>
                <Space direction='vertical'>
                    <QRCode value={text || "-"}/>
                    <Input
                        placeholder='-'
                        maxLength={60}
                        value={text}
                        onChange={(e)=>setText(e.target.value)}
                    />
                </Space>
                <QRCode
                    errorLevel={"L"}
                    value="https://ant.design/"
                    icon="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg"
                />
                <QRCode value={text} status="loading" />
                <QRCode value={text} status="expired" onRefresh={() => console.log('refresh')} />
                <QRCode value={text} status="scanned" />
            </Space>
        </Card> 
    )
}

/**
 * Segmented 分段控制器
 */
const SegmentedWidget=()=>{
    const optionsList = [
        "Daily",
        {
            label:"weekly",
            value:"weekly",
            disabled:true,
            icon: <SearchOutlined />,
        },
        "monthly",
        {
            label:"Quarterly",
            value:"Quarterly",
            disabled:true
        },
        "yearly"
    ]

    const [options,setOptions] = useState(['Daily', 'Weekly', 'Monthly'])
    const [moreLoaded, setMoreLoaded] = useState(false);
    const handleLoadOptions=()=>{
        setOptions((prev)=>[...prev,'Quarterly', 'Yearly']) // 这里的prev是setOptions的hook会接受一个参数，这个参数代表数据的前一个状态内容
        setMoreLoaded(true)
    }
    return(
        <Card title="Segmented 分段控制器">
            <Space>
                <Segmented options={optionsList}/>
                <Divider type="vertical" />
                <Space direction='vertical'>
                    <Segmented options={options}/>
                    <Button type='primary' disabled={moreLoaded} onClick={handleLoadOptions}>加载更多选项</Button>
                </Space>
            </Space>
        </Card>
    )
}
/**
 * Statistic 统计数值 AND 倒计时Countdown 
 */
const StatisticWidget=()=>{

    const {Countdown} = Statistic
    const deadLine = Date.now() + 1000*60*60*24*2+1000*30

    const onFinish=()=>{
        console.log('finished!');
    }
    const onChange = (val) => {
        if (typeof val === 'number' && 4.95 * 1000 < val && val < 5 * 1000) {
          console.log('changed!');
        }
      };
    
    return(
        <Card title="Statistic 统计数值 | 倒计时Countdown">
            <Flex wrap gap={"large"}>
                <Statistic title="Active Users" value={2232434} />
                <Statistic title="Feedback" value={2233} prefix={<LikeOutlined />}/>
                <Statistic title="Unmerged" value={43} suffix={"/100"}/>
                <Statistic
                    title="Idle"
                    value={9.3676}
                    precision={2}
                    valueStyle={{
                        color: '#cf1322',
                    }}
                    prefix={<ArrowDownOutlined />}
                    suffix="%"
                    />
            </Flex>
            <Row gutter={5}>
                <Col span={12}>
                    <Countdown title="Countdown" value={deadLine} onFinish={onFinish} />
                </Col>
                <Col span={12}>
                    <Countdown title="Million Seconds" value={deadLine} format="HH:mm:ss:SSS" />
                </Col>
                <Col
                span={24}
                style={{
                    marginTop: 32,
                }}
                >
                    <Countdown title="Day Level" value={deadLine} format="D 天 H 时 m 分 s 秒" />
                </Col>
                <Col span={12}>
                    <Countdown title="Countdown" value={Date.now() + 10 * 1000} onChange={onChange} />
                </Col>
            </Row>
        </Card>
    )
}

/**
 * Tag 标签
 */
const TagWidget=()=>{
    const preventDefault=(e)=>{
        e.preventDefault()
        console.log('Clicked! But prevent default.');
    }

    const onClose=()=>{
        console.log('关了tag了');
    }

    const tagsData = ['Movies', 'Books', 'Music', 'Sports'];
    const [selectedTags,setSelectedTags] = useState(["Movies"])
    const handleChange = (tag,checked)=>{
        const nextSelectedTags = checked
            ? [...selectedTags,tag]
            : selectedTags.filter((t)=>t!==tag)
        setSelectedTags(nextSelectedTags);
    }

    return(
        <Card title="Tag 标签">
            <Space>
                <Tag>标签1</Tag>
                <Tag>
                    <a href='https://www.baidu.com'>百度连接</a>
                </Tag>
                <Tag closeIcon onClose={preventDefault}>Prevent Default</Tag>
                <Tag closeIcon={<CloseCircleOutlined />} onClose={onClose}>标签2</Tag>
                <Tag color={"magenta"}>magenta</Tag>
                <Tag color={"purple"}>purple</Tag>
                <Tag icon={<TwitterOutlined />} color="#55acee">Twitter</Tag>
            </Space>
            <Flex 
            gap={4} 
            wrap 
            align={"center"}
            style={{
                marginTop:20
            }}
            >
                <span>Categories:</span>
                {tagsData.map((tag)=>(
                    <Tag.CheckableTag 
                        key={tag}
                        checked={selectedTags.includes(tag)}
                        onChange={(checked)=>handleChange(tag,checked)}
                    >
                        {tag}
                    </Tag.CheckableTag>
                ))}
            </Flex>
        </Card>
    )
}

/**
 * Tag 可以动态添加修改的标签
 * 1.删除列表中的数据可以用filter，将不同于要删除的内容筛选成新的列表。 tags.filter((tag)=>tag!==removedTag)
 * 2.向列表赋值，解构旧列表，和新数据拼接成一个新列表赋值。setTags([...tags,inputValue])
 */
const DynamicTagWidget=()=>{
    const [tags, setTags] = useState(['Unremovable', 'Tag 2', 'Tag 3']);
    // 输入新标签的内容和输入框是否显示
    const [inputVisible, setInputVisible] = useState(false);
    const [inputValue, setInputValue] = useState('');
    // 改变标签内容的index和value
    const [editInputIndex, setEditInputIndex] = useState(-1);
    const [editInputValue, setEditInputValue] = useState('');

    const inputRef = useRef(null);
    const editInputRef = useRef(null);

    useEffect(()=>{
        if(inputVisible){
            inputRef.current?.focus()
        }
    },[inputVisible])

    useEffect(()=>{
        editInputRef.current?.focus();
    },[editInputValue])

    // 删除掉这个tag
    const handleClose =(removedTag)=>{
        const newTags = tags.filter((tag)=>tag!==removedTag)
        console.log(newTags)
        setTags(newTags)
    }

    // 显示输入框
    const showInput=()=>{
        setInputVisible(true)
    }

    // 设置新输入框内容
    const handleInputChange =(e)=>{
        setInputValue(e.target.value)
    }

    // 将新输入框内容设置到tags列表中。
    const handleInputConfirm=()=>{
        if(inputValue && !tags.includes(inputValue)){
            setTags([...tags,inputValue])
        }
        setInputVisible(false)
        setInputValue("")
    }

    // 设置编辑tag内容
    const handleEditInputChange=(e)=>{
        setEditInputValue(e.target.value)
    }

    // 当点击回车确定输入内容时，将内容替换到tag列表中对应index的内容。
    const handleEditInputConfirm=()=>{
        const newtags = [...tags]
        newtags[editInputIndex] = editInputValue
        setTags(newtags)
        setEditInputIndex(-1)
        setEditInputValue("")
    }
    const { token } = theme.useToken();
    const tagPlusStyle = {
        height: 22,
        background: token.colorBgContainer,
        borderStyle: 'dashed',
      };
    const tagInputStyle = {
        width: 64,
        height: 22,
        marginInlineEnd: 8,
        verticalAlign: 'top',
      };

      return(
        <Card title="Tag 可以动态添加修改的标签">
            <Flex gap={"4px 4px"} wrap>
                {
                    tags.map((tag,index)=>{
                        if(editInputIndex === index){
                            return(
                                <Input
                                    ref={editInputRef}
                                    key={tag}
                                    size='small'
                                    style={tagInputStyle}
                                    value={editInputValue}
                                    onChange={handleEditInputChange}
                                    onBlur={handleEditInputConfirm} // 输入框失去焦点的时候回调
                                    onPressEnter={handleEditInputConfirm}
                                />
                            )
                        }
                        const isLongTag = tag.length>10
                        const tagElem = (
                            <Tag
                            key={tag}
                            closable={index !== 0}
                            style={{
                                userSelect:"none"
                            }}
                            onClose={()=>handleClose(tag)}
                            >
                                <span
                                onDoubleClick={(e)=>{
                                    if(index !== 0){
                                        setEditInputIndex(index)
                                        setEditInputValue(tag)
                                        e.preventDefault()
                                    }
                                }}
                                >
                                    {isLongTag?`${tag.slice(0,10)}...`:tag}
                                </span>
                            </Tag>
                        )
                        return isLongTag?(
                            <Tooltip title={tag} key={tag}>
                                {tagElem}
                            </Tooltip>
                        ):(tagElem);
                    })
                }
                {
                    inputVisible?(
                        <Input
                        ref={inputRef}
                        type='text'
                        size='small'
                        style={tagInputStyle}
                        value={inputValue}
                        onChange={handleInputChange}
                        onBlur={handleInputConfirm}
                        onPressEnter={handleInputConfirm}
                        />
                    ):(
                        <Tag style={tagPlusStyle} icon={<PlusOutlined />} onClick={showInput}>
                            新标签
                        </Tag>
                    )
                }
            </Flex>
        </Card>
      )

}
/**
 * TimeLine 时间轴  &  Tooltip  文字提示
 */
const TimeLineWidget=()=>{
    const items1 = [
        {
            color:"green",
            children:"gagag"
        },
        {
            color:"red",
            children:"vfdvfvf"
        },
        {
            color:"gray",
            children:(
                <>
                    <p>hahah1</p>
                    <p>hahah2</p>
                    <p>hahah3</p>
                </>
            )
        },
        {
            color:"green",
            children:"gagag",
            dot:<ClockCircleOutlined />,
        }
    ]

    const items2 = [
        {
          label: '2015-09-01',
          children: 'Create a services',
        },
        {
          label: '2015-09-01 09:12:11',
          children: 'Solve initial ',
        },
        {
          children: 'Technical testing',
        },
        {
          label: '2015-09-01 09:12:11',
          children: 'Network prob',
        },
      ]

    const items3=[
        {
          children: 'Create a servi',
        },
        {
          children: 'Solve initial n',
          color: 'green',
        },
        {
          dot: (
            <ClockCircleOutlined
              style={{
                fontSize: '16px',
              }}
            />
          ),
          children: `Sed ut perspiciatis.`,
        },
        {
          color: 'red',
          children: 'Network problems ',
        },
        {
          children: 'Create a services site 2015-09-01',
        },
        {
          dot: (
            <ClockCircleOutlined
              style={{
                fontSize: '16px',
              }}
            />
          ),
          children: 'Technical testing 2015-09-01',
        },
      ]

    return(
        <Card title="TimeLine 时间轴  与  Tooltip 文字提示">
            <Space size={"large"}>
                <Timeline items={items1}/>
                <Divider type='vertical' style={{height:300}}/>
                <Timeline items={items2} mode={"left"}/>
                <Divider type='vertical' style={{height:300}}/>
                <Timeline items={items3} mode={"alternate"}/>
                <Divider type='vertical' style={{height:300}}/>
                <Space direction='vertical'>
                    <Tooltip title={"文字提示"}>
                        <Button>文字提示</Button>
                    </Tooltip>
                    <Tooltip placement="topRight" title={"文字提示"}>
                        <Button>文字提示TR</Button>
                    </Tooltip>
                    <Tooltip title={"文字提示"} color='green'>
                        <Button>文字提示color</Button>
                    </Tooltip>
                </Space>
            </Space>
        </Card>
    )
}


const DateShowWidget =()=>{
    return(
      <Space direction='vertical'>
        <Space direction='horizontal'>
            <AvatarWidget/>
            <CarouselWidget/> 
        </Space>
        <DescriptionsWidget/>
        <TourWidget/>
        <QRCodeWidget/>
        <SegmentedWidget/>
        <StatisticWidget/>
        <TagWidget/>
        <DynamicTagWidget/>
        <TimeLineWidget/>
      </Space>
    )
}

export default DateShowWidget